import { Injectable, BadRequestException } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository, In } from 'typeorm'
import { Router } from './entities/router.entity'
import { Role } from './entities/role.entity'

@Injectable()
export class RouterService {
  constructor(
    @InjectRepository(Router) private readonly router: Repository<Router>,
    @InjectRepository(Role) private readonly role: Repository<Role>
  ) {}

  async findAll() {
    try {
      const data = await this.router.find({
        order: {
          _id: 'ASC'
        }
      })
      return { data, message: '获取路由成功' }
    } catch (error) {
      throw new BadRequestException(error.message)
    }
  }

  async findOne(rid: number) {
    const role = await this.role.findOne({
      where: { role_id: rid },
      select: ['router_ids']
    })
    if (!role || !role.router_ids) {
      throw new BadRequestException(`Role with ID ${rid} not found!`)
    } else {
      const data = await this.router.find({
        where: {
          id: In(role.router_ids)
        }
      })
      return { data, message: '获取路由成功' }
    }
  }
}
